﻿/*
 * Created by SharpDevelop.
 * Date: 23.10.2011 г.
 * Time: 13:49 ч.
 * 
 */
using System;
using System.ComponentModel;
using System.IO;
using System.Collections.Generic;
using System.Windows.Forms;

namespace CaesarCoder
{
	public class Config
	{
		public Config()
		{
			this.ConfigDirectory = "";
			this.ConversionTables = new BindingList<ConversionTable>();
		}
		
		public Config(string ConfigDirectory)
		{
			this.ConversionTables = new BindingList<ConversionTable>();
			if (ConfigDirectory != null && ConfigDirectory.Length > 0 && Directory.Exists(ConfigDirectory))
			{
				this.ConfigDirectory = ConfigDirectory;
				string[] cfgfiles = Directory.GetFiles(ConfigDirectory, "*.cfg");
				foreach (string cfgfile in cfgfiles)
				{
					ConversionTable ct = new ConversionTable(cfgfile);
					if (ct.isValid())
					{
						this.ConversionTables.Add(ct);
					}
				}
			} //if
			else
			{
				this.ConfigDirectory = "";
				if (!Directory.Exists(ConfigDirectory)) Directory.CreateDirectory(ConfigDirectory);
			}
		}
		
		/// <summary>
		/// Reloads the ConversionTable objects
		/// </summary>
		/// <returns>true - if valid ConversionTable objects found, false - if no ConversionTable objects found or if Configdirectory does not exist</returns>
		public bool Reload()
		{
			this.ConversionTables = new BindingList<ConversionTable>();
			if (this.ConfigDirectory != null && this.ConfigDirectory.Length > 0 && Directory.Exists(this.ConfigDirectory))
			{
				int ct_num = 0;
				string[] cfgfiles = Directory.GetFiles(ConfigDirectory, "*.cfg");
				foreach (string cfgfile in cfgfiles)
				{
					ConversionTable ct = new ConversionTable(cfgfile);
					if (ct.isValid())
					{
						ct_num++;
						this.ConversionTables.Add(ct);
					}
				}
				return (ct_num > 0);
			} //if
			else
			{
				return false;
			}
		}
		
		/// <summary>
		/// Checks if the given name already exists in the collection
		/// </summary>
		/// <param name="Name">The name of the table</param>
		/// <returns>true - if the name is already taken, false - otherwise</returns>
		public bool ContainsTable(string Name)
		{
			if ((this.ConversionTables == null) || !(this.ConversionTables.Count > 0))
			{
				return false;
			}
			
			foreach (ConversionTable table in ConversionTables)
			{
				if (Name == table.Name)
				{
					return true; //Name is already taken
				}
			}
			return false;
		}
		
		/// <summary>
		/// Contains the path to the directory where the ConversionTable objects are stored
		/// </summary>
		public string ConfigDirectory {get; set;}
		
		// BindingList<T> used instead of just List<T> so that it can be bound to a DataGridView
		// and we can add/remove items from the view and they reflect immediately to the BindingList
		public BindingList<ConversionTable> ConversionTables {get; set;}
	}
}
